﻿

<div class="ui-widget mb ilb">
    <div class="ui-widget-header ui-corner-top">Data Runs</div>
    <div id="DataRunProgress" class="ui-widget-content ui-corner-bottom"></div>
</div> 

<div></div>

    <div class="ui-widget mt ilb">
        <div class="ui-widget-header ui-corner-top">
            <span class="ui-icon ui-icon-document ilb"></span>Data Set Load Progress
        </div>
        <div class="ui-widget-content ui-corner-bottom pad">
           
            <div class="ui-widget">
                <div class="ui-widget-header ui-corner-top">Progress</div>
                <div class="ui-widget-content ui-corner-bottom">

                    <p>
                        The progress of your dataset uploads are displayd below. Uploads that were completed more than a day ago are not displayed.
                    </p>
                    <p>
                    <table id="ProgressTable">
                        <thead>
                        <tr>
                            <th>DataSet</th>                                
                            <th>Progress</th>
                            <th>Email</th>
                            <th>Pushover</th>
                            
                                                      
                        </tr>
                            </thead>

                        <tbody>

                        </tbody>
                    </table>
                        </p>
                </div>
            </div>
           
            

        </div>
    </div>



<script type="text/javascript">

    ///<reference path="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js" />
    ///<reference path="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js" />
    ///<reference path="js/lib.js" />
    ///<reference path="js/md5.js" />

    var _UpdateDataRunProgressInterval;

    $(document).ready(function ()
    {
        // console.log("trackprogress");
        $("#DataRunProgress").jsontable();

        UpdateProgressTable();

        UpdateDataRunProgressTable();
        if(_UpdateDataRunProgressInterval == null)
          _UpdateDataRunProgressInterval = setInterval(UpdateDataRunProgressTable, 5000);

    });

    function PageCleanup()
    {
       // console.log("Page Cleanup");
      //  console.log(_UpdateDataRunProgressInterval);
        clearInterval(_UpdateDataRunProgressInterval);
        _UpdateDataRunProgressInterval = null;
      //  console.log(_UpdateDataRunProgressInterval);
        
    }


    function UpdateDataRunProgressTable()
    {
        GetJsonSproc("usp_GetStatusOfPendingDataRuns",
            function (json) {


                var now = new Date();

                $("#DataRunProgress").siblings(".ui-widget-header").text("Data Runs (" + json.length + ")");

               $.each(json, function (key, item)
                {
                   item.Perc = (item.Perc);// + "%";
                   var started;

                   if (item.StartedProcessing == null)
                       started = now;
                   else
                       started = new Date(item.StartedProcessing);
                   
                   item.Pushover = item.Pushover == 1;
                   item.Email = item.Email == 1;



                   item.TimeProcessingHours = Math.floor((now.getTime() - started.getTime()) / 1000 / 60 / 60); // hours
                   item.TimeProcessingMinutes = Math.floor((now.getTime() - started.getTime()) / 1000 / 60 % 60); // mins

                   var minutesSpent = (now.getTime() - started.getTime()) / 1000 / 60;

                   var totalMinutes = minutesSpent / item.Perc;

                   var minsRemaining = totalMinutes - minutesSpent;

                   item.RemainingMins = Math.floor(minsRemaining % 60);
                   item.RemainingHours = Math.floor(minsRemaining / 60);

                });

                $("#DataRunProgress").jsontable("option", {
                    source: json,
                    noData : "No pending or in-progress requests.",
                    columnOrder: ["commandblock", "Title", "DataSetName", "TimeProcessing", "RemainingTime", "SourceObjects", "Perc", "ClientId", "Is3D"],
                    columnDefs:
                        {
                            commandblock:
                                {
                                    Format: "commandblock",
                                    HeaderText : "",
                                    Items : [
                                        {
                                            ActionName: "delete",
                                            Icon: "fa fa-trash-o"
                                        }
                                    ],
                                    ItemClick: function(action, dataItem, tr)
                                    {
                                        switch(action)
                                        {
                                            case "delete":
                                                {
                                                    if (confirm("Are you sure you wish to delete this data run? This will remove related data results and KS Tests"))
                                                    {
                                                        GetJsonSproc("usp_DeleteDataRun",
                                                       {
                                                           DataRunRequestId: dataItem.id
                                                       },
                                                       function () {
                                                           tr.remove();
                                                           Growl("Data Run Removed.");
                                                       });
                                                    }
                                                    break;
                                                }
                                        }
                                    },


                                },
                            Is3D : { Format: "boolean", HeaderText: "3D" },
                            Perc: {
                                Format: "function",
                                FormatFunction: function(val)
                                {
                                    var n = new Number(val);
                                    n *= 100;

                                    if (n ==  100)
                                    {
                                        return "Uploading..."
                                    }
                                    else
                                    {
                                       
                                        return n.toFixed(2) + "%";
                                    }
                                }
                            },
                            SourceObjects: { Format: "number" },
                            ProcessedObjects: { Format: "number" },
                            StartedProcessing: { Format: "datetime" },
                            Distance: { Format: "number" },
                                        

                            TimeProcessing: 
                            {
                                HeaderText: "Time Spent",
                                Format: "function",
                                FormatFunction: function(val, dataItem)
                                {
                                    if (dataItem.Completed == 0)
                                        return PrecedingZeroTwoDigits(dataItem.TimeProcessingHours) + ":" + PrecedingZeroTwoDigits(dataItem.TimeProcessingMinutes);
                                    else
                                        return dataItem.MinutesToProcess + " min";
                                }
                            },
                            RemainingTime:
                                {
                                    HeaderText: "Est. Remaining",
                                    Format: "function",
                                    FormatFunction: function (val, dataItem)
                                    {
                                        return  dataItem.StartedProcessing == null || dataItem.Completed == 1 ? "n/a" :  PrecedingZeroTwoDigits(dataItem.RemainingHours) + ":" + PrecedingZeroTwoDigits(dataItem.RemainingMins);
                                    }
                                }
                        }
                })
            });


      
    }

    function UpdateProgressTable()
    {



        GetJsonSproc("usp_GetDataSetLoadProgress",
           {
               UserId: localStorage.getItem("UserId")
           },
       function (json)
       {
           var tbl = $("#ProgressTable > tbody:first");
           tbl.empty();
           //console.log(json);
           $.each(json, function (key, value)
           {
               var r = $("<tr>");

               var processing = value["Processing"];
               var processed = value["Processed"];
               
               r.append($("<td>").text(value["Name"]));


               if (processing || processed)
               {

                   var pbar = $("<span style=''>").progressbar(
                       {
                           max: value["TotalRows"],
                           change: function ()
                           {
                               var max = $(this).progressbar("option", "max");
                               var v = $(this).progressbar("value");
                               var p = new Number((v / max) * 100.00);

                               v = Math.round(v);

                               $(this).parent().children(".progress-status").text(v + " / " + max + " (" + p.toPrecision(3) + "%)");
                           },
                           complete: function ()
                           {
                             //  Growl("Dataset loaded.");
                           }
                       });

                   $(pbar).width(130).height(10);

                   var td = $("<td>").append(pbar);

                   r.append(td);
                   td.append("<span class='progress-status'>");
                  // console.log(value["RowsProcessed"]);
                   pbar.progressbar("value", value["RowsProcessed"]);

                   //  r.append($("<span>").text("df"));
               }
               else
               {
                   var pbar = $("<span style=''>").progressbar(
                       {
                           max: 100,
                           value: 0
                       });

                   $(pbar).width(130).height(10);


                   var td = $("<td>").append(pbar);
                   td.append($("<span class='progress-status'>").text("Not Started (0%)"));
                   r.append(td);



               }

               // Progress: <span id="progressbar" style='width: 300px;'>               
               //</span><span class="progress-status">Loading...</span>

               if (value["Email"])
                   r.append($("<td>").html("<span class='ui-icon ui-icon-check'>"));
               else
                   r.append($("<td>").text(""));



               if (value["Pushover"])
                   r.append($("<td>").html("<span class='ui-icon ui-icon-check'>"));
               else
                   r.append($("<td>").text(""));

               tbl.append(r);
           });



       });

    //   ProgressTableTimeout =  setTimeout(UpdateProgressTable, 5000);


    }


</script>

